/*
 Copyright (C) 2009 are of bakabt
 boxtorrents, azureus, vuze, and java are copyrighted to their respective owner.

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; version 2 of the License.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */
package com.boxtorrents.azureus.action;

import java.net.MalformedURLException;
import java.net.URL;

import org.gudy.azureus2.plugins.PluginInterface;
import org.gudy.azureus2.plugins.config.ConfigParameter;
import org.gudy.azureus2.plugins.config.ConfigParameterListener;
import org.gudy.azureus2.plugins.download.Download;
import org.gudy.azureus2.plugins.download.DownloadCompletionListener;
import org.gudy.azureus2.plugins.download.DownloadException;
import org.gudy.azureus2.plugins.logging.LoggerChannel;
import org.gudy.azureus2.plugins.ui.config.StringListParameter;

import com.boxtorrents.azureus.BoxTorrentsPlugin;
import com.boxtorrents.azureus.PluginParamConstants;
import com.boxtorrents.azureus.StatCheckEvent;
import com.boxtorrents.azureus.StatCheckListener;
import com.boxtorrents.azureus.Util;

/**
 * @author are of bakabt.com
 */
public class TrackerChangerAction implements StatCheckListener {
	private static final long serialVersionUID = 6245934917493257247L;
	private static final PluginInterface pi = BoxTorrentsPlugin
	    .getPluginInterface();
	private static final LoggerChannel log = BoxTorrentsPlugin.getLog();
	private static DownloadCompletionListener completionListener;
	private static boolean actenable = false;

	/**
	 * 
	 */
	public TrackerChangerAction() {
		completionListener = new DownloadCompletionListener() {
			public void onCompletion(Download d) {
				doRedirectBox(new Download[] { d });
			}
		};
		pi.getPluginconfig().getPluginParameter(
		    PluginParamConstants.PR_DOWNLOAD_HANDLER).addConfigParameterListener(
		    new ConfigParameterListener() {
			    public void configParameterChanged(ConfigParameter cnf) {
				    if (cnf instanceof StringListParameter) {
					    StringListParameter par = (StringListParameter)cnf;
					    actenable = par.getValue().equals("tracker");
					    onEnabled(actenable);
				    }
			    }
		    });
		if (isEnabled()) onEnabled(true);
	}

	/**
	 * @inheritDoc
	 */
	public boolean isEnabled() {
		return actenable;
	}

	/**
	 * @inheritDoc
	 */
	public void onCheckResult(StatCheckEvent e) {
		if (isEnabled()) {
			if (e.getEventType() == StatCheckEvent.EVENT_DANGER) {
				// redirect to alternative tracker
				int num = doRedirectAlt(pi.getDownloadManager().getDownloads());
				if (num > 0
				    && pi.getPluginconfig().getPluginBooleanParameter(
				        PluginParamConstants.PR_DOWNLOAD_HANDLER_ALERT, false)) {
					log.logAlert(LoggerChannel.LT_INFORMATION, "redirecting " + num
					    + " download(s) to alternative tracker");
				}
			} else if (e.getEventType() == StatCheckEvent.EVENT_NORMAL) {
				// redirect to box tracker
				int num = doRedirectBox(pi.getDownloadManager().getDownloads());
				if (num > 0
				    && pi.getPluginconfig().getPluginBooleanParameter(
				        PluginParamConstants.PR_DOWNLOAD_HANDLER_ALERT, false)) {
					log.logAlert(LoggerChannel.LT_INFORMATION, "redirecting " + num
					    + " download(s) to boxtorrents tracker");
				}
			}
		}
	}

	private int doRedirectBox(Download[] downloads) {
		URL url = null;
		try {
			url = Util.getBoxtorrentsTrackerURL();
		} catch (MalformedURLException e) {
			log.logAlert("Passkey error", e);
		}
		if (url == null) return 0;

		int num = 0;
		for (Download d : downloads) {
			if (!d.isComplete() && Util.isBoxtorrentsDownload(d)
			    && !Util.isBoxtorrentsTracker(d)) {
				try {
					if (d.getState() != Download.ST_QUEUED) d.stopAndQueue();
				} catch (DownloadException e) {
					log.log(e);
				}
				d.getTorrent().setAnnounceURL(url);
				log.log("redirect to box: " + d.getName());
				num++;
			}
		}
		return num;
	}

	private int doRedirectAlt(Download[] downloads) {
		URL url = null;
		try {
			url = Util.getAlternativeTrackerURL();
		} catch (MalformedURLException e) {
			log.logAlert("Error while try to redirect to alternative tracker", e);
		}
		if (url == null) return 0;

		int num = 0;
		for (Download d : downloads) {
			if (!d.isComplete() && Util.isBoxtorrentsDownload(d)
			    && Util.isBoxtorrentsTracker(d)) {
				try {
					if (d.getState() != Download.ST_QUEUED) d.stopAndQueue();
				} catch (DownloadException e) {
					log.log(e);
				}
				d.getTorrent().setAnnounceURL(url);
				log.log("redirect to alt: " + d.getName());
				num++;
			}
		}
		return num;
	}

	/**
	 * @inheritDoc
	 */
	public void onEnabled(boolean enable) {
		if (enable) {
			pi.getDownloadManager().getGlobalDownloadEventNotifier()
			    .addCompletionListener(completionListener);
		} else {
			pi.getDownloadManager().getGlobalDownloadEventNotifier()
			    .removeCompletionListener(completionListener);
		}
	}
}
